from models import *
from datetime import datetime

def isUserLoggedIn(request):
	if 'user' in request.session:
		return True
	else:
		return False

def getLoggedInUser(request):
	if isUserLoggedIn(request):
		userobj = User.objects.get(id=request.session['user'])
		return userobj
	else:
		return None

def logOff(request):
	try:
		userobj = User.objects.get(id=request.session['user'])
		del request.session['user']
		request.session.flush()
		
		userobj.save()
		
		return True
	except:
		return False

def logIn(request, username):
	try:
		userobj = User.objects.get(username=username, account_status=1)
		userobj.last_login = datetime.now()
		userobj.save()
		request.session['user'] = userobj.id
		return True
	except User.DoesNotExist:
		return False



